from app.Mapper.OrderMapper  import OrderMapper
from app.Mapper.ThingMapper import ThingMapper
from app.Mapper.UserMapper import UserMapper
from app.db import db


class OrderService:
    def __init__(self,db):
        self.order_mapper = OrderMapper(db)

    def list_orders(self, page, page_size):
        """分页查询订单"""
        orders, total = self.order_mapper.list_orders(page, page_size)

        result = {
            'total': total,
            'page': page,
            'pageSize': page_size,
            'list': []
        }

        for order in orders:
            order_dict = {
                'id': order.id,
                'order_number': order.order_number,
                'order_time': order.order_time.strftime('%Y-%m-%d %H:%M:%S') if order.order_time else None,
                'receiver_name': order.receiver_name,
                'title': ThingMapper(db).get_thing(order.thing_id).title,
                'status': order.status,
                'totalAmount': order.count * ThingMapper(db).get_thing(order.thing_id).price,
                # 'username': UserMapper(db).get_by_id(order.user_id).username,
                # 'count': order.count,
                # 'receiver_address': order.receiver_address,
                # 'receiver_phone': order.receiver_phone,
                # 'remark': order.remark
            }
            result['list'].append(order_dict)

        return result

    def delete_order(self, order_id):
        """删除订单"""
        self.order_mapper.delete(order_id)

    def delete_orders(self, ids):
        """批量删除订单"""

        self.order_mapper.batch_delete(ids)